import {Link} from 'react-router-dom'

function openTab (record, dispatch, callback) {
  const {prefix, name, route} = record
  const tab = {
    name: `${prefix}-${name}`,
    route,
  }

  dispatch({
    type: 'app/addTab',
    payload: {
      menu: tab,
    },
  })

  if (callback) {
    callback()
  }
}

export function updateOrder (record, dispatch) {
  const {id, sn} = record
  openTab({
    prefix: '更新订单',
    name: sn,
    route: `/orderForm/${id}`,
  }, dispatch)

  dispatch({
    type: 'createOrder/updateState',
    payload: {
      formType: 'update',
      current: record,
    },
  })
}

export function getOrderLink (record, dispatch) {
  const {id, sn} = record

  return (
    <Link to={`/orders/${id}`} onClick={() => openTab({
      prefix: '订单',
      name: sn,
      route: `/orders/${id}`,
    }, dispatch)}>{sn}</Link>
  )
}

export function getOperatorLink ({wxNo, wxId}, dispatch) {

  return (
    <Link to={'/operator/'.concat(wxId)}
          onClick={() => openTab({
            prefix: '运营号',
            name: wxNo || wxId,
            route: `/operator/${wxId}`,
          }, dispatch)}>{wxNo || wxId}</Link>
  )
}

export function getCustomerLink ({cid, owxId, name, val}, dispatch) {

  return (
    <Link
      to={`/customer/${cid}?owxId=${owxId}`}
      onClick={() => openTab({
        prefix: '好友',
        name,
        route: `/customer/${cid}`,
      }, dispatch)}>{val}</Link>
  )
}

export function getChatroomLink (record, dispatch) {

  return (
    <Link to={'/chatroom/'.concat(record.id)} onClick={() => {
      openTab({
        prefix: '群聊',
        name: record.chatroomName || record.chatroomId,
        route: `/chatroom/${record.chatroomId}`,
      }, dispatch, () => {
        dispatch({
          type: 'chatroomDetail/getDetail',
          payload: {
            data: record,
          },
        })
      })
    }}>{record.chatroomId}</Link>
  )
}
